package com.example.ywj.toutiao.fragments;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.ywj.toutiao.DetailActivity;
import com.example.ywj.toutiao.R;
import com.example.ywj.toutiao.bean.News;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.MyBaseAdapter;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Fragment1 extends Fragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "Fragment1";
    private View view;
    //是否可见
    public boolean isVisible = false;
    //是否初始化完成
    public boolean isInit = false;
    //是否已经加载过
    public boolean isLoadOver = false;
    public  String title;
    public PullToRefreshListView  pullToRefreshListView;
    private String baseUrl = Constant.BASEURL;
    private List<News> list = new ArrayList<>();
    private MyBaseAdapter myBaseAdapter;
    private Integer page = 0;
    public List<News> showList;
    public List<News> showList2;
    public List<News> showList3;
    public Integer totalPage;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null){
            view = inflater.inflate(R.layout.fragment1, null);
            isInit = true;
            setParam();
            //initView(view);
        }
        return view;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisible = isVisibleToUser;
        setParam();
    }
    private void setParam() {
        if (isInit && !isLoadOver && isVisible) {
            isLoadOver = true;
            title = getArguments().getString("title");
            //TextView tv1 = view.findViewById(R.id.tv_title);
            //tv1.setText(title);
            getTotalPage();
            getData(title);
            //myListView = view.findViewById(R.id.mylistview);
            pullToRefreshListView = view.findViewById(R.id.pull_refresh_list);
            pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
            ILoadingLayout down =pullToRefreshListView.getLoadingLayoutProxy(true,false);//设置下拉文字
            ILoadingLayout up= pullToRefreshListView.getLoadingLayoutProxy(false,true);
            down.setPullLabel("下拉刷新");// 刚下拉时，显示的提示
            down.setRefreshingLabel("拼命刷新中");// 刷新时
            down.setReleaseLabel("放开刷新");// 下来达到一定距离时，显示的提示
            down.setLoadingDrawable(getResources().getDrawable(R.drawable.refresh));
            up.setLoadingDrawable(getResources().getDrawable(R.drawable.refresh));
            up.setPullLabel("加载更多");
            up.setRefreshingLabel("拼命加载中");
            up.setReleaseLabel("放开加载");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }
    public void getTotalPage(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getTotalPage();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                    //Log.i(TAG, "onResponse: "+json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code==200&&obj.has("count")){
                    totalPage = obj.get("count").getAsInt();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }

    private void getData(final String title){
        //Log.i(TAG, "getTitle: "+title);
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getNews(title,page);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                    //Log.i(TAG, "onResponse: "+json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray objArr = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    list = gson.fromJson(objArr,new TypeToken<ArrayList<News>>(){}.getType());
                    //lastPage = list.get(list.size()-1).getPage();
                    //Log.i(TAG, "onResponse: "+lastPage);
                    showList = new ArrayList<>();
                    for(int i=0;i<list.size();i++){
                        if(list.get(i).getIsDetele() == 0){
                            showList.add(list.get(i));
                        }
                    }
                    myBaseAdapter = new MyBaseAdapter(showList);
                    pullToRefreshListView.setAdapter(myBaseAdapter);
                    pullToRefreshListView.setOnItemClickListener(Fragment1.this);
                    pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                        @Override
                        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                            Retrofit retrofit = new Retrofit.Builder()
                                    .addConverterFactory(GsonConverterFactory.create())
                                    .baseUrl(baseUrl)
                                    .build();
                            ResponseApi responseApi = retrofit.create(ResponseApi.class);
                            Call<ResponseBody> call = responseApi.getNews(title,++page);
                            call.enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    String json = null;
                                    try {
                                        json = response.body().string();
                                        //Log.i(TAG, "onResponse: "+json);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    JsonObject obj = (JsonObject)new JsonParser().parse(json);
                                    Integer code = obj.get("statusCode").getAsInt();
                                    if(code == 200 && obj.has("data")){
                                        JsonArray objArr = obj.getAsJsonArray("data");
                                        Gson gson = new Gson();
                                        List<News> newList = gson.fromJson(objArr,new TypeToken<ArrayList<News>>(){}.getType());
                                        //刷新listview
                                        showList2 = new ArrayList<>();
                                        for(int i=0;i<newList.size();i++){
                                            if(newList.get(i).getIsDetele() == 0){
                                                showList2.add(newList.get(i));
                                            }
                                        }
                                        showList.clear();
                                        showList.addAll(showList2);
                                        myBaseAdapter.notifyDataSetChanged();
                                        pullToRefreshListView.onRefreshComplete();
                                        //Log.i(TAG, "onResponse: "+page);
                                        if(newList.size()!= 10){
                                            page = -1;
                                        }else if(newList.get(newList.size()-1).getPage()==totalPage){
                                            page = -1;
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    //Toast.makeText(Fragment1.this,"您的网络抽风了",Toast.LENGTH_LONG).show();
                                    Log.i(TAG, "onFailure: 出错了");
                                }
                            });

                        }

                        @Override
                        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                            Retrofit retrofit = new Retrofit.Builder()
                                    .addConverterFactory(GsonConverterFactory.create())
                                    .baseUrl(baseUrl)
                                    .build();
                            ResponseApi responseApi = retrofit.create(ResponseApi.class);
                            Call<ResponseBody> call = responseApi.getNews(title,++page);
                            call.enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    String json = null;
                                    try {
                                        json = response.body().string();
                                        Log.i(TAG, "onResponse: "+json);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    JsonObject obj = (JsonObject)new JsonParser().parse(json);
                                    Integer code = obj.get("statusCode").getAsInt();
                                    if(code == 200 && obj.has("data")){
                                        JsonArray objArr = obj.getAsJsonArray("data");
                                        Gson gson = new Gson();
                                        List<News> newList = gson.fromJson(objArr,new TypeToken<ArrayList<News>>(){}.getType());
                                        showList3 = new ArrayList<>();
                                        for(int i=0;i<newList.size();i++){
                                            if(newList.get(i).getIsDetele() == 0){
                                                showList3.add(newList.get(i));
                                            }
                                        }
                                        //list.clear();
                                        showList.addAll(showList3);
                                        myBaseAdapter.notifyDataSetChanged();
                                        pullToRefreshListView.onRefreshComplete();
                                        if(newList.size()!= 10){
                                            page = -1;
                                        }else if(newList.get(newList.size()-1).getPage()==totalPage){
                                            page=-1;
                                        }
                                    }
                                }
                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    //Toast.makeText(Fragment1.this,"您的网络抽风了",Toast.LENGTH_LONG).show();
                                    Log.i(TAG, "onFailure: 出错了");
                                }
                            });

                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 出错了");
            }
        });

    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Log.i(TAG, "onItemClick: "+position);
        //Log.i(TAG, "onItemClick: "+"长度"+list.size());
        Bundle bundle = new Bundle();
        bundle.putString("id",showList.get(position-1).get_id());
        bundle.putString("otherUser",showList.get(position-1).getUsername());
        Intent intent = new Intent(parent.getContext(),DetailActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
